#!/usr/bin/python2.6
#
# Python Oracle VM Server Management
#
# Copyright (C) 2011 ovm Project
# Author: Choonho Son <choonho@kt.com>
# URL: <http://ovm.googlecode.com>
# For license information, see LICENSE.TXT
#

import time
import re
from subprocess import Popen, PIPE, call

class Command(object):
    '''
    classdocs
    '''

    def execute(self, cmd, sh=False):
        cmdToken = cmd.split(" ")
        r = Popen(cmdToken, stdin=PIPE, stdout=PIPE, stderr=PIPE, shell=sh).communicate()
        #r:(stdout, stderr)
        return r

    
    def findall(self, pattern, cmd_result):
        """
        @param pattern: search pattern
        @param result: command line execution result
        @return : list of search
        find result of command which has same pattern
        findall command find all pattern in a string
        """
        result = []
        for line in cmd_result.split("\n"):
            items = re.findall(pattern, line)
            for item in items:
                result.append(item)
        return result
    
    def checkPattern(self, pattern, cmd_result):
        """
        @param pattern: search pattern
        @param cmd_result: command line execution result
        @return : True (if pattern is occurred)
        """
        for line in cmd_result:
            items = re.findall(pattern, line)
            if len(items) > 0:
                return True
        return False
    
    def search(self, cmd_result, pattern):
        return None
    
class CmdError(Exception):
    def __init__(self, msg):
        self.msg = msg
    def __str__(self):
        return repr(self.msg)

class PreconditionError(Exception):
    def __init__(self, msg):
        self.msg = msg
    def __str__(self):
        return repr(self.msg)
                        
